package cn.sonui.onlinechat.utils;

import cn.sonui.onlinechat.bean.InteractiveData;
import cn.sonui.onlinechat.bean.MessageInfo;
import cn.sonui.onlinechat.bean.RoomInfo;
import cn.sonui.onlinechat.bean.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import static cn.sonui.onlinechat.utils.OnlineChat.*;

public class MessageHandle {
    private InteractiveData data = new InteractiveData();
    private static final Logger log = LoggerFactory.getLogger(MessageHandle .class);
    public MessageHandle(){}
    public MessageHandle(InteractiveData data){
        this.data = data;
    }

    public Integer bindWebSockeet(Session session, String token){
        Integer uid = livingCache.getOrDefault(token, -1);
        if (uid != -1){
            UserInfo t = userCache.get(uid);
            javax.websocket.Session c = t.getSession();
            if (c != null && c.isOpen()) {
                //log.info("");
                try{
                    c.close();
                } catch (IOException e){
                    log.error(e.getMessage());
                }
            }
            t.setSession(session);
            userCache.put(uid, t);
            log.info(String.format("ws[%s] bind session ok%n", session.getId()));
            return 1;
        }else{
            return 2;
        }
    }

    private Boolean sessionSend(Integer uid, MessageInfo msg){
        UserInfo user = userCache.get(uid);
        InteractiveData sendData = new InteractiveData();
        sendData.setCode(7);
        sendData.setMsg(msg.getMessage());
        sendData.setMsgInfo(msg);
        Session s = user.getSession();
        if (s.isOpen()){
            s.getAsyncRemote().sendText(JSON.toJSONString(sendData, SerializerFeature.BrowserCompatible));
            return true;
        }
        return false;
    }
    public Integer sendMessage(Integer roomId, MessageInfo msgInfo){
        log.info(String.format("roomId[%d], msg[%s], type[%d]", roomId, msgInfo.getMessage(), msgInfo.getType()));
        RoomInfo room =  roomCache.get(roomId);
        if(room == null) return 0;
        if (msgInfo.getType() == 1){
            List<Integer> userL = room.getMember();
            log.info(String.format("Room Member Num[%d]", userL.size()));
            AtomicReference<Integer> ans = new AtomicReference<>(0);
            userL.forEach((id) -> {
                if (sessionSend(id, msgInfo))
                    ans.getAndSet(ans.get() + 1);
            });
            return ans.get();
        }else if(msgInfo.getType() == 2){
            if (sessionSend(msgInfo.getRecipient(), msgInfo))
                return 1;
            return 0;
        }
        return 0;
    }
}
